import { DatePicker, Form, Input, Modal, Select, message } from 'antd';
import { useRef } from 'react';
import { addTask } from '../../../services/task';
import { palaceAppointTimeList, palaceIdTypeList, palaceTicketTypeList } from '../config';

interface PalaceFormProps {
  onClose: () => void;
}

const PalaceForm = (props: PalaceFormProps) => {
  const [form] = Form.useForm();
  const saving = useRef(false);

  const handlerAdd = () => {
    if (saving.current) {
      return;
    }
    saving.current = true;
    form.validateFields().then((values) => {
      const saveData = {
        appointDate: values.appointDate.format('YYYY-MM-DD'),
        appointTime: values.appointTime,
        platform: 2,
        touristList: [
          {
            name: values.touristName,
            idType: values.idType,
            idNo: values.idNo,
            ticketType: values.ticketType
          }
        ]
      };

      addTask(saveData).then((res: any) => {
        saving.current = false;
        if (res.data.code === 200) {
          props.onClose();
        } else {
          message.warning(res.data.message);  
        }
      }, (err: any) => {
        saving.current = false;
        message.warning(err);
      });
    }, () => {
      saving.current = false;
    });
  };

  return (
    <Modal open={true} onCancel={props.onClose} width={700} onOk={handlerAdd}>
      <Form
        style={{ padding: 24 }}
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          label="预约日期"
          name="appointDate"
          rules={[{ required: true, message: '请选择预约日期' }]}
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="预约时段"
          name="appointTime"
          rules={[{ required: true, message: '请选择预约时段' }]}
        >
          <Select style={{ width: '100%' }} placeholder="请选择时段" options={palaceAppointTimeList} />
        </Form.Item>
        <Form.Item
          label="预约票种"
          name="ticketType"
          rules={[{ required: true, message: '请选择预约票种' }]}
        >
          <Select style={{ width: '100%' }} placeholder="请选择预约票种" options={palaceTicketTypeList} />
        </Form.Item>
        <Form.Item
          label="游客姓名"
          name="touristName"
          rules={[{ required: true, message: '请填写游客姓名' }]}
        >
          <Input placeholder='请输入姓名' />
        </Form.Item>
        <Form.Item
          label="证件类型"
          name="idType"
          rules={[{ required: true, message: '请选择证件类型' }]}
        >
          <Select style={{ width: '100%' }} placeholder="请选择证件类型" options={palaceIdTypeList} />
        </Form.Item>
        <Form.Item
          label="证件号码"
          name="idNo"
          rules={[{ required: true, message: '请输入证件号码' }]}
        >
          <Input placeholder='请输入证件号码' />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default PalaceForm;
